<template>
  <view class="order-page flex flex-col px-32rpx h-full box-border">
    <view class="flex justify-between">
      <up-checkbox :customStyle="{ marginBottom: '8px' }" activeColor="#1a5fa9" usedAlone :checked="batch"
        @change="batchCheckChange">
      </up-checkbox>
      <view v-if="selectKeys.length">
        <view class=" flex items-center">
          <view class="mr-10rpx text-black text-28rpx">批量填写</view>
          <view class="w-228rpx">
            <up-input type="number" v-model="batchDay" @blur="(val) => handleBatchInput(val)" placeholder="请输入到仓货期">
            </up-input>
          </view>
        </view>
        <view v-if="batchError" class="text-24rpx text-#F53F3F ml-130rpx">{{ batchError }}</view>
      </view>
    </view>
    <view class="flex-1 overflow-auto">
      <view class="order-item my-48rpx" v-for="(item, index) in skuList" :key="index">
        <!-- 产品 -->
        <view class="flex justify-between items-center">
          <view class="flex items-center">
            <up-checkbox :disabled="item.disable" :customStyle="{ marginBottom: '8px' }" activeColor="#1a5fa9"
              :name="index" usedAlone :checked="item.checked" @change="(val) => checkChange(val, item)">
            </up-checkbox>
            <view class="common-product-list-item-left ml-10rpx">
              <up-album :urls="[item.skuImageUrl || defaultImg]"></up-album>
              <view>
                <view class="name">
                  {{ item?.skuDescription || '' }}
                </view>
                <view class="sub-name">
                  需求数量：{{ item?.skuPcs || '' }}
                </view>
              </view>
            </view>
          </view>
          <view>
            <view class="w-228rpx">
              <view v-if="item.skuDeliveryDateText">
                {{ item.skuDeliveryDateText }}
              </view>
              <up-input v-else type="number" :disabled="item.disable" v-model="item.deliveryDays"
                @blur="(val) => handleInput(val, item)" placeholder="请输入到仓货期">
              </up-input>
            </view>
            <view v-if="!!item.error" class="text-24rpx text-#F53F3F">{{ item.error }}</view>
          </view>
        </view>
      </view>
    </view>
    <view class="h-148rpx w-full box-border items-center justify-around flex py-26rpx">
      <up-button color="#1A5FA9" type="primary" text="确认订单" @click="save"></up-button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { poManageQueryPoSku, poManageUpdatePoSku } from "@/genapi/poManage"
import { supplierPoApprovalOrderConfirm } from "@/genapi/supplierPoApproval"
import defaultImg from "@/static/default.png"
import { computed } from "vue";

const skuList = ref([])
let detailId = ''
// const selectKeys = ref<any[]>([])
// const batch = ref<boolean>(false)
const batchDay = ref()
const batchError = ref('')
const selectKeys = computed(() => {
  const skuArr = []
  if (skuList.value.length) {
    skuList.value.map(item => {
      if (item.checked && !item.disable)
        skuArr.push(item)
    })
    return skuArr
  } else {
    return []
  }
})
const batch = computed(() => !!selectKeys.value.length)
onLoad((query) => {
  detailId = query?.id || ''
})
function batchCheckChange(val) {
  if (!val) batchDay.value = ''
  const skuArr = skuList.value.map((item: any) => {
    if (!item.disable) {
      item.checked = val
    }
    return item
  })
  skuList.value = [...skuArr]
}
function checkChange(val, item) {
  item.checked = val
}
// 批量失焦
async function handleBatchInput(val: string) {
  if (+val > 730) {
    batchError.value = '货期不能超过730天'
    return
  }
  // 使用正则表达式验证输入值是否为正整数
  if (!val) {
    batchError.value = '请输入到仓货期'
    return
  }
  if (+val >= 1 && /^-?\d*\.?\d*$/.test(val)) { // 小数或整数
    // 正数
    batchDay.value = Math.floor(+val).toString();
    batchError.value = ''
    const updateList: any[] = selectKeys.value.map((item: any) => {
      return {
        deliveryDays: +batchDay.value,
        id: item.id,
      }
    })
    const res = await updateDeliverDays({ updateList })
    if (res) {
      getSkuList()
    }
  } else {
    batchDay.value = ''
    batchError.value = '请输入到仓货期'
  }
}
async function handleInput(val: string, item: any) {
  if (+val > 730) {
    item.error = '货期不能超过730天'
    return
  }
  if (!val) return
  // 使用正则表达式验证输入值是否为正整数
  if (+val >= 1 && /^-?\d*\.?\d*$/.test(val)) { // 小数或整数
    item.deliveryDays = Math.floor(+val).toString();
    item.error = ''
  } else {
    item.deliveryDays = ''
    return
  }
  const skuInfo: any = {
    deliveryDays: +item.deliveryDays,
    id: item.id,
  }
  const res = await updateDeliverDays({ updateList: [skuInfo] })
  if (res) {
    item.disable = true
    item.checked = false
  }
}
// 修改货期
async function updateDeliverDays(params: any) {
  const { data } = await poManageUpdatePoSku(params)
  if (data?.code !== 200) return false
  uni.showToast({
    title: '货期修改成功',
    icon: 'none'
  })
  return true
}
async function getSkuList() {
  batchDay.value = ''
  const { data } = await poManageQueryPoSku({ poId: detailId, noCancelSku: true })
  if (data?.code !== 200) return
  else {
    const result = data.data
    skuList.value = result.map((item: any) => {
      item.disable = !!item.skuDeliveryDateText
      item.error = ''
      return item
    })
  }
}
async function save() {
  if (skuList.value.length) {
    if (batchDay.value) {
      handleBatchInput(batchDay.value)
    }
    let valid = true
    const newList = skuList.value.map(item => {
      if (!item.disable && !item.deliveryDays) {
        item.error = '请输入到仓货期'
        valid = false
      } else if (item.deliveryDays > 730) {
        item.error = '货期不能超过730天'
        valid = false
      }
      return item
    })
    skuList.value = [...newList]
    if (!valid) return
    const params: any = { poOrderId: detailId }
    const { data } = await supplierPoApprovalOrderConfirm(params)
    if (data?.code !== 200) return
    uni.showToast({
      title: '订单已确认,请及时发货',
      icon: 'success'
    })
    uni.navigateBack({
      delta: 1
    })
  }
}
onShow(async () => {
  getSkuList()
})
</script>
